<script lang="tsx">
import { defineComponent, ref, watch, nextTick } from 'vue';
import { $t } from '@vben/locales';
import BaseDrawer from '#/components/common/base-drawer.vue';
import { getTeamMembersApi } from '#/api/competition/team-info';
import { usePage } from '#/hooks/page/usePage';
import { IdCard } from '@vben/icons';
import ObsImage from '#/components/obsImage.vue';
import { ElMessage } from 'element-plus';

export default defineComponent({
  name: 'TeamInfoForm',
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    teamData: {
      type: Object,
      default: () => ({}),
    }
  },
  emits: ['update:modelValue', 'cancel'],
  setup(props, { emit }) {
    const imageUploadRef = ref();
    const dialogVisible = ref(false);
    const visible = ref(false);
    const columns = [
      {
        type: 'index',
        label: $t('common.numberIdxTxt'),
        width: 60,
        align: 'center',
        prop: 'index'
      },
      {
        prop: 'name',
        label: $t('competition.teamInfo.memberName'),
        minWidth: 120,
        showOverflowTooltip: true,
      },
      {
        prop: 'role',
        label: $t('competition.teamInfo.memberRole'),
        minWidth: 80,
        formatter: (row: any) => {
          const roleMap: Record<number, string> = {
            1: $t('competition.teamInfo.captain'),
            2: $t('competition.teamInfo.viceCaptain'),
            3: $t('competition.teamInfo.member')
          };
          const role = Number(row.role);
          return <span>{roleMap[role] || '--'}</span>
        }
      },
      {
        prop: 'position',
        label: $t('competition.teamInfo.memberPosition'),
        minWidth: 100,
      },
      {
        prop: 'phone',
        label: $t('competition.teamInfo.memberPhone'),
        minWidth: 120,
      },
      {
        prop: 'email',
        label: $t('competition.teamInfo.memberEmail'),
        minWidth: 150,
        formatter: (row: any) => {
          return <span style={{ textDecoration: row.email ? 'underline' : 'none' }}>{row.email || '--'}</span>
        }
      },
    ];

    // 操作按钮配置
    const commands = [
      {
        key: 'show',
        width: 60,
        label: $t('common.viewTxt'),
        icon: IdCard,
        render: (row: any, index?: number) => {
          return (
            <el-tooltip
              effect="dark"
              content={$t('competition.teamInfo.showCertificate')}
              show-after={600}
              placement="top"
            >
              <el-button
                link
                icon={IdCard}
                onClick={() => tableHandle('show', row, index)}
              />
            </el-tooltip>
          );
        },
      },

    ];

    // 自定义操作处理
    const handleCommand = (action: string, row: any, index?: number) => {
      console.log('action:', action);
      console.log('row:', index);
      if (action === 'show') {
        // 展示证书
        console.log('row:', row);
        // 确保 photoName 是有效的字符串
        const photoName = row.photoName;
        if (photoName && typeof photoName === 'string') {
          imageUploadRef.value = photoName;
          console.log('imageUploadRef.value:', imageUploadRef.value);
          dialogVisible.value = true;
        } else {
          ElMessage.error($t('competition.teamInfo.photoNameError'));
        }
      }
    };
    const { render, tableHandle, getTableData } = usePage({
      API: {
        get: (data: any) => {
          if (!props.teamData?.teamId) return Promise.resolve({ data: [], total: 0 });
          let params = { ...data };
          params.teamId = props.teamData?.teamId || '';
          return getTeamMembersApi(params)
        }
      },
      queryColumns: [],
      columns,
      pageClass: ['members-page'],
      commands,
      handleCommand
    });

    // 监听 modelValue 变化
    watch(() => props.modelValue, (val) => {
      visible.value = val;
      if (val) {
        getTableData();
        // 重置 use-page 下第一个子元素 div 的样式
        nextTick(() => {
          const usePageElement = document.querySelector('.members-page');
          const contentHeight = document.querySelector('.el-drawer__body')?.clientHeight || 0;
          if (usePageElement) {
            // 往上2层的父级div
            const parentDiv = usePageElement.parentElement?.parentElement;
            if (parentDiv) {
              // 强制覆盖动态样式，删除 calc 计算样式
              parentDiv.setAttribute('style', `height: auto !important; padding: 0 !important; --vben-content-height: ${contentHeight - 54}px !important;`);
            }
          }
        });
      }
    }, { deep: true });

    // 处理关闭
    const handleClose = () => {
      emit('update:modelValue', false);
      emit('cancel');
    };

    // 关闭图片
    const handleImageClose = () => {
      dialogVisible.value = false;
    };

    return () => (
      <BaseDrawer
        modelValue={visible.value}
        title={$t('competition.teamInfo.membersInfo')}
        onUpdate:modelValue={(val: boolean) => emit('update:modelValue', val)}
        onClose={handleClose}
        showFooter={false}
        v-slots={{
          footer: () => (
            <el-button onClick={handleClose}>{$t('common.cancelTxt')}</el-button>
          )
        }}
      >
        <div class="w-full h-full">
          {
            visible.value && render({
              table: {
                prefix: () => [] // 覆盖默认的 prefix，不包含 serialColumn
              }
            })
          }
          {
            visible.value && <el-dialog
              modelValue={dialogVisible.value}
              onUpdate:modelValue={(val: boolean) => dialogVisible.value = val}
              width="600px"
              align-center
              center
              destroy-on-close={true}
              title={$t('competition.teamInfo.showCertificate')}
              append-to-body={true}
              close-on-click-modal={false}
              before-close={handleImageClose}
            >
              <div class="min-h-[300px]">
                {
                  imageUploadRef.value && <ObsImage showPreview={false} src={imageUploadRef.value} />
                }
              </div>
            </el-dialog>
          }
        </div>
      </BaseDrawer>
    );
  },
});
</script>

<style lang="scss" scoped>
.members-page {
  height: 100%;
}
</style>
